package top.codedance.iotp.client.manage.net.com232;

import top.codedance.iotp.client.manage.ManageApplication;
import com.fazecast.jSerialComm.SerialPort;
import com.sshtools.forker.client.ForkerProcess;
import org.apache.log4j.Logger;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ClientRunner implements Runner, Runnable {
    private Logger logger = ManageApplication.getLogger(ClientRunner.class);
    private ForkerProcess p;
    private SerialPort serialPort;
    private static Pattern startPattern = Pattern.compile("<!\\[\\[");
    private static Pattern endPattern = Pattern.compile("\\]\\]-->");
    private static Pattern contextPattern = Pattern.compile("<!\\[\\[(.+)\\]\\]-->", Pattern.DOTALL | Pattern.MULTILINE);
    private boolean isRunning = true;

    public ClientRunner(ForkerProcess p) {
        this.p = p;
    }

    public void stop(){
        isRunning = false;
    }

    @Override
    public byte[] exec(byte[] data) {
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(p.getOutputStream(), Charset.forName(System.getProperty("sun.jnu.encoding"))));
        try {
            bw.write(new String(data, StandardCharsets.UTF_8));
            bw.flush();
        }catch (Exception e){
            logger.debug(e.getMessage());
        }
        return new byte[0];
    }

    @Override
    public byte[] exec(byte[] data, SerialPort serialPort) {
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(p.getOutputStream(), Charset.forName(System.getProperty("sun.jnu.encoding"))));
        this.serialPort = serialPort;
        try {
            bw.write(new String(data, StandardCharsets.UTF_8));
            bw.flush();
        }catch (Exception e){
            logger.debug(e.getMessage());
        }
        return new byte[0];
    }

    @Override
    public void run() {
        BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream(), Charset.forName(System.getProperty("sun.jnu.encoding"))));
        while (isRunning) {
            try {
                StringBuilder sb = new StringBuilder();
                boolean reading = false;
                String line;
                Matcher matcher;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                    matcher = startPattern.matcher(sb.toString());
                    if(matcher.find()){
                        reading = true;
                    }
                    if(reading){
                        matcher = endPattern.matcher(sb.toString());
                        if(matcher.find()){
                            matcher = contextPattern.matcher(sb.toString());
                            if(matcher.find()) {
                                String s = matcher.group(0).replaceAll(startPattern.toString(), "").replaceAll(endPattern.toString(), "");
                                logger.debug("Client return context: " + s);
                                byte[] bytes = s.getBytes(StandardCharsets.UTF_8);
                                serialPort.writeBytes(bytes, bytes.length);
                            }
                            sb = new StringBuilder();
                            reading = false;
                        }
                    }else{
                        ManageApplication.syslogInfo(line);
                    }
                }
            } catch (Exception e) {
                logger.debug(e.getMessage());
            }
            try {
                Thread.sleep(100);
            } catch (Exception e) {
            }
        }
    }
}
